package org.ahuanlien.crm.service.impl;

import org.ahuanlien.crm.domain.Menu;
import org.ahuanlien.crm.domain.Permission;
import org.ahuanlien.crm.domain.Role;
import org.ahuanlien.crm.mapper.RoleMapper;
import org.ahuanlien.crm.query.QueryObject;
import org.ahuanlien.crm.service.IRoleService;
import org.ahuanlien.crm.util.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

@Service
public class RoleServiceImpl implements IRoleService {



	@Autowired
	private RoleMapper roleMapper;


	public List<Role> selectAll() {
		return roleMapper.selectAll();
	}

	public PageResult query(QueryObject qo) {
		int count = roleMapper.queryForCount(qo);
		if (count == 0) {
			return new PageResult(count, Collections.EMPTY_LIST);
		}
		List<Role> result = roleMapper.queryForList(qo);
		return new PageResult(count, result);
	}

	public void saveOrUpdate(Role record) {
		if (record.getId() != null) {
			roleMapper.removePermissionRelation(record.getId());
			roleMapper.removeMenuRelation(record.getId());
			for (Permission permission : record.getPermissions()) {
				roleMapper.savePermissionRelation(record.getId(),permission.getId());
			}
			for (Menu menu : record.getMenus()) {
				roleMapper.saveMenuRelation(record.getId(),menu.getId());
			}
			roleMapper.updateByPrimaryKey(record);
		} else {
			roleMapper.insert(record);
			for (Permission permission : record.getPermissions()) {
				roleMapper.savePermissionRelation(record.getId(),permission.getId());
			}
			for (Menu menu : record.getMenus()) {
				roleMapper.saveMenuRelation(record.getId(),menu.getId());
			}
		}
	}

	public void deleteByPrimaryKey(Long id) {
		roleMapper.removePermissionRelation(id);
		roleMapper.removeMenuRelation(id);
		roleMapper.deleteByPrimaryKey(id);
	}

	public List<Long> getRoleIdByEmployeeId(Long employeeId) {
		return roleMapper.getRoleIdByEmployeeId(employeeId);
	}

	public List<Long> getMenuIdByRoleId(Long roleId) {
		return roleMapper.getMenuIdByRoleId(roleId);
	}

	public List<String> getRoleNameByEmployeeId(Long id) {
		return roleMapper.getRoleNameByEmployeeId(id);
	}
}
